package com.epfresh.supplier.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.AgentMoneyDetailActivity;
import com.epfresh.supplier.activity.BaseStoreInfoActivity;
import com.epfresh.supplier.adapter.AgentMyApplyViewBinder;
import com.epfresh.supplier.adapter.*;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.*;
import com.epfresh.supplier.entity.AgentMyApplyRecord;
import com.epfresh.supplier.entity.AgentMyRecord;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.SaveEntity;
import com.epfresh.supplier.activity.*;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.WrapContentLinearLayoutManager;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Created by zzq on 2017/12/4.
 */
public class AgentMyRecordFragment extends BaseFragment {

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    AgentMyRecordViewBinder agentMyRecordViewBinder;
    LinearLayoutManager mManager;
    RecyclerView rv;

    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    int pageNum = 0;

    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }


    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqAgentRecord(pageNum + 1);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_agent_record,
                container, false);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            reqAgentRecord(0);
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_agent_record);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    AgentMyRecord.ProductsBean bean;
    String mModifyName, mModifyPhone;

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        initHeadView(v);
        rv = v.findViewById(R.id.rv_make_agent);
        mManager = new WrapContentLinearLayoutManager(getContext());
        rv.setLayoutManager(mManager);
        mMultiAdapter = new MultiTypeAdapter();
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);
        agentMyRecordViewBinder = new AgentMyRecordViewBinder();
        agentMyRecordViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                Intent intent;
                if (data instanceof AgentMyRecord.ProductsBean)
                    bean = (AgentMyRecord.ProductsBean) data;
                switch (view.getId()) {
                    case R.id.tv_agent_modify:
                        openModifyDialog();
                        break;
                    case R.id.tv_agent_record_go:
                        intent = new Intent(getContext(), BaseStoreInfoActivity.class);
                        intent.putExtra("baseStoreId", bean.getFather().getId());
                        intent.putExtra("mHasAgent", false);
                        startActivity(intent);
                        break;
                    case R.id.rl_agent_record_goods:
//                        intent = new Intent(getContext(), AgentMoneyDetailActivity.class);
//                        intent.putExtra("baseStoreId", bean.getFather().getId());
//                        startActivity(intent);

                        intent = new Intent(getContext(), BaseProductDetailActivity.class);
                        intent.putExtra("baseStoreId", bean.getFather().getId());
                        intent.putExtra("productId", bean.getId());
                        startActivity(intent);
                        break;
                    case R.id.rl_agent_record_more:
                        intent = new Intent(getContext(), AgentMoneyDetailActivity.class);
                        intent.putExtra("baseStoreId", bean.getFather().getId());
                        startActivity(intent);
                        break;
                    case R.id.sw_agent_record:
                        openAgentStoreDialog(bean.getFather().getName());//获取到基地店铺的名称
                        break;
                    case R.id.goods_agent_record_sw:
                        openGoodsAgentStoreDialog(bean.getTitle());//获取到商品名称
                        break;
                }
            }
        });
        mMultiAdapter.register(AgentMyRecord.ProductsBean.class, agentMyRecordViewBinder);
        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rv.setAdapter(mMultiAdapter);
//        mMultiAdapter.setItems(mItems);
        reqAgentRecord(pageNum);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x002) {// && resultCode == 0x001) {
            // initNotice();
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    List<Object> mBaseStores = new ArrayList<>();

    public void reqAgentRecord(int pageNum) {
        if (getActivity() == null) {
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_AGENT_MYAGENTS);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("pageSize", 10);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_AGENT_MYAGENTS, onAgentRecordRequestListener);
    }

    private OnRequestListener<ContentEntity<AgentMyRecord>> onAgentRecordRequestListener = new OnRequestListener<ContentEntity<AgentMyRecord>>() {
        @Override
        public ContentEntity<AgentMyRecord> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, AgentMyRecord.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<AgentMyRecord>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
            ContentEntity<AgentMyRecord> responseElement = response.getResponseElement();
            boolean last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<AgentMyRecord> content = responseElement.getContent();
            //第一页
            pageNum = number;
            if (pageNum == 0) {
                mBaseStores.clear();
                mItems.clear();
                Log.e("代办记录数据项", mItems.size() + "");
            }
            for (int i = 0; i < content.size(); i++) {
                if (content.get(i).getProducts() == null || content.get(i).getProducts().size() == 0) {
                    List<AgentMyRecord.ProductsBean> list = new ArrayList<>();
                    list.add(new AgentMyRecord.ProductsBean());
                    content.get(i).setProducts(list);
                }
                for (int j = 0; j < content.get(i).getProducts().size(); j++) {
                    content.get(i).getProducts().get(j).setFather(content.get(i));
                    if (j == 0) {
                        content.get(i).getProducts().get(j).setFirstFlag(true);
                    }
                    if (j < 2)
                        mItems.add(content.get(i).getProducts().get(j));
                    if (j == 1) {
                        if (content.get(i).getProducts().size() > 2) {
                            content.get(i).getProducts().get(j).setMoreFlag(true);
                        } else {
                            content.get(i).getProducts().get(j).setMoreFlag(false);
                        }
//                        mItems.add(content.get(i).getProducts().get(j));
                    }
                }
            }

            Log.e("代办记录数据项", mItems.size() + "");

            if (mBaseStores.size() == 0) {
                loadMoreDelegate.setStatusEmpty();
                loadMoreDelegate.addLoadItemOnly(mItems);
            } else {
                loadMoreDelegate.addAllItem(mItems, mBaseStores);
            }
            //最后一个
            if (last) {
                loadMoreDelegate.setStatusNoMore();
            } else {
                loadMoreDelegate.setStatusNormal();
            }
            mMultiAdapter.setItems(mItems);
            mMultiAdapter.notifyDataSetChanged();

        }
    };
    private AgentSwitchDialog deleteDialog;

    /**
     * 这个是针对单个商品代办
     */
    private void openGoodsAgentStoreDialog(String goodsName) {
        final AgentSwitchDialog goodsAgentDialog = new AgentSwitchDialog(getContext(), true);
        if (bean.getState() == 0) {
            goodsAgentDialog.setTitle("是否开启商品代办？");
            goodsAgentDialog.setMessage("开启代办后，将接收" + goodsName + "代办订单");
        } else {
            goodsAgentDialog.setTitle("是否暂停商品代办？");
            goodsAgentDialog.setMessage("如暂停代办，将不会有新的" + goodsName + "的代办订单 但是正在进行中的订单请完成");
        }
        goodsAgentDialog.setOnPositiveClickListener("确定", new AgentSwitchDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener() {
                goodsAgentDialog.dismiss();
               switchGoodsStoreState() ;

            }

        });
        goodsAgentDialog.setOnNegativeClickListener("取消", new AgentSwitchDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                goodsAgentDialog.dismiss();
                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
            }
        });
        goodsAgentDialog.show();
    }


    private void openAgentStoreDialog(String baseStoreName) {
        deleteDialog = new AgentSwitchDialog(getContext(), true);
        if (bean.getFather().getAgentStatus() == 4) {
            // 是否开启代办？
            deleteDialog.setTitle("是否开启代办？");
            //  开启代办后，将接收宁夏枸杞种植基地的代办订单
            deleteDialog.setMessage("开启代办后，将接收" + baseStoreName + "基地的代办订单");
        } else {
            //是否暂停代办？
            deleteDialog.setTitle("是否暂停代办？");
            //如暂停代办，将不会有新的宁夏枸杞种植基地代办订单 但是正在进行中的订单请完成
            deleteDialog.setMessage("如暂停代办，将不会有新的" + baseStoreName + "的代办订单 但是正在进行中的订单请完成");
        }
        deleteDialog.setOnPositiveClickListener("确定", new AgentSwitchDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener() {
                deleteDialog.dismiss();
                switchAgentStoreState();
            }

        });
        deleteDialog.setOnNegativeClickListener("取消", new AgentSwitchDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                deleteDialog.dismiss();
                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
            }
        });
        deleteDialog.show();
    }

    /**
     * 店铺单个商品的代办状态
     * storeId  基地id
     * productId 商品id
     * agentStoreId  代办店铺id
     * state 商品状态
     */
    private void switchGoodsStoreState() {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_GOODS_AGENT_STATES);
        RequestEntityMapSupply.putParameter("storeId", bean.getFather().getId());
        RequestEntityMapSupply.putParameter("productId", bean.getId());
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());

        if (bean.getState() == 0)
            RequestEntityMapSupply.putParameter("state", 1);
        else {
            RequestEntityMapSupply.putParameter("state", 0);
        }
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_GOODS_AGENT_STATES, onGoodsSwitchRequestListener);
    }
    private OnRequestListener<SaveEntity> onGoodsSwitchRequestListener = new OnRequestListener<SaveEntity>() {
        @Override
        public SaveEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveEntity.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<SaveEntity> response, Object tag) {
            hideProgressDialog();
            SaveEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                if (bean.getState() == 0) {
                    bean.setState(1);
//                    reqAgentRecord(0);
                }
                else{
                    bean.setState(0);
                    mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
                }
                reqAgentRecord(0);
//                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
//                if (((MakeAgentActivity) getAppActivity()).makeAgentFragment != null) {
//                    ((MakeAgentActivity) getAppActivity()).makeAgentFragment.reqSupplyStoreDyn(0);
//                }
            } else {
                T.toast("设置失败，请稍后重试");
            }
        }
    };

    /**
     * 代办店铺的开关
     */
    private void switchAgentStoreState() {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_AGENT_STATES);
        RequestEntityMapSupply.putParameter("storeId", bean.getFather().getId());
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        if (bean.getFather().getAgentStatus() == 4)
            RequestEntityMapSupply.putParameter("state", 2);
        else
            RequestEntityMapSupply.putParameter("state", 4);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_AGENT_STATES, onSwitchRequestListener);
    }

    private OnRequestListener<SaveEntity> onSwitchRequestListener = new OnRequestListener<SaveEntity>() {
        @Override
        public SaveEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveEntity.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<SaveEntity> response, Object tag) {
            hideProgressDialog();
            SaveEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                if (bean.getFather().getAgentStatus() == 4){
                    bean.getFather().setAgentState(2);
                    mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
                }
                else {
                    bean.getFather().setAgentState(4);
//                    reqAgentRecord(0);
                }
                reqAgentRecord(0);
//                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
//                if (((MakeAgentActivity) getAppActivity()).makeAgentFragment != null) {
//                    ((MakeAgentActivity) getAppActivity()).makeAgentFragment.reqSupplyStoreDyn(0);
//                }

            } else {
                T.toast("设置失败，请稍后重试");
            }
        }
    };


    private AgentModifyDialog modifyDialog;

    private void openModifyDialog() {
        modifyDialog = new AgentModifyDialog(getContext(), true);

        modifyDialog.initDate(bean);
        modifyDialog.setOnPositiveClickListener("确定", new AgentModifyDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener(String name, String phone) {
                if (name == null || "".equals(name)) {
                    T.toast("请填写收货人");
                    return;
                }
                if (phone == null || "".equals(phone)) {
                    T.toast("请填写收货人电话");
                    return;
                }
                modifyDialog.dismiss();
                modify(name, phone);
            }

        });
        modifyDialog.setOnNegativeClickListener("取消", new AgentModifyDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                modifyDialog.dismiss();
            }
        });
        modifyDialog.show();
    }


    private void modify(String name, String phone) {


        if (getActivity() == null) {
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_AGENT_MODIFY);
        RequestEntityMapSupply.putParameter("storeId", bean.getFather().getId());//基地店铺ID
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());//代办店铺ID
        RequestEntityMapSupply.putParameter("consigneePhone", phone);
        RequestEntityMapSupply.putParameter("consigneeName", name);

        mModifyName = name;
        mModifyPhone = phone;
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_AGENT_MODIFY, onModifyRequestListener);
    }

    private OnRequestListener<SaveEntity> onModifyRequestListener = new OnRequestListener<SaveEntity>() {
        @Override
        public SaveEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveEntity.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast(arg.toString());
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<SaveEntity> response, Object tag) {
            hideProgressDialog();
            SaveEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                T.toast("修改成功");
                bean.getFather().setConsigneeName(mModifyName);
                bean.getFather().setConsigneePhone(mModifyPhone);
                mMultiAdapter.notifyItemChanged(mItems.indexOf(bean));
            } else {
                T.toast("修改失败，请稍后重试");
            }
        }
    };


}
